package dbtask

import (
	"fmt"
	daogext "github.com/darwinOrg/daog-ext"
	dgctx "github.com/darwinOrg/go-common/context"
	dgcron "github.com/darwinOrg/go-cron"
	dglock "github.com/darwinOrg/go-dlock"
	"github.com/rolandhe/daog"
)

var (
	TimeoutMinutesMap map[string]int
	RetentionDays     int
)

func InitTimeoutCron() {
	cron := dgcron.NewAndStart(dglock.NewDbLocker(daogext.GetDatasource()))

	if len(TimeoutMinutesMap) > 0 {
		cron.AddJobWithLock("重新初始化超时任务", "0 0/5 * * * ?", 5000, func(ctx *dgctx.DgContext) {
			_ = daogext.Write(ctx, func(tc *daog.TransContext) error {
				ctx.NotLogSQL = true

				for taskType, timeoutMinutes := range TimeoutMinutesMap {
					_, _ = ReInitTimeoutProcessingTasks(ctx, taskType, timeoutMinutes)
				}

				return nil
			})
		})
	}

	if RetentionDays > 0 {
		cron.AddJobWithLock(fmt.Sprintf("删除%d天前的任务", RetentionDays), "0 0 3 * * ?", 5000, func(ctx *dgctx.DgContext) {
			_ = daogext.Write(ctx, func(tc *daog.TransContext) error {
				return DeleteOverdueTasks(ctx, RetentionDays)
			})
		})
	}
}
